<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 10:32
 */

namespace app\adminapiv3\controller;

//安装
use app\adminapiv3\service\InstallService;
use app\adminapiv3\service\platform_manage\ServerAuthService;
use app\common\model\FilePathModel;
use think\Db;
use think\Request;

class InstallController extends BaseController
{
    /**
     * 一. 同意协议
     * 二. 授权
     * 三. 数据库地址设置,生成数据库
     * 四. 添加代理服务器ip port
     * 五. 添加系统管理员
     * 六. 入库(授权信息)
     */
    private $installDir = './Install/';
    /**
     * @name 检查是否安装
     * @author wx
     * @date 2019/11/28 14:53
     */
    private function isInstall()
    {
        $model = new FilePathModel();
        $installFileName = $model->install_path;
        $systemFileName = $model->system_time;

        if(!file_exists($this->installDir)){
            mkdir($this->installDir, 0777, true);
        }
        
        //创建syslog上传目录
        $syslogDir = '../runtime/Syslog/';
        if(!file_exists($syslogDir)){
            mkdir($syslogDir,0777,true);
        }

        if (file_exists($installFileName) && file_exists($systemFileName) ) {
            returnErrJson(121, '您已完成安装,请勿重复安装');
        }
    }


    /**
     * @name 在线授权
     * @author wx
     * @date 2019/11/28 10:55
     */
    public function online(Request $request)
    {
        $this->isInstall();

        $params = $request->only(['key']);


        $this->validate($params,'Install.online');

        returnErrJson($this->CODE_FAIL,'此功能暂未开放');

        $authServer = new ServerAuthService();
        $serverInfo = $authServer->getPlatformBaseInfo();

        $requestData = array(

            'serial_number' => $params['key'],
            'ip' => $_SERVER['SERVER_ADDR'],
            'system' => $serverInfo['os'],
            'alias' => $serverInfo['alias'],
            'uuid' => $serverInfo['hostkey'],
        );

        $url = config('request_auth_url');
        $authRes = requestCurl($url,1,$requestData);

        if($authRes['code'] != 0){
            returnErrJson($authRes['code'], $authRes['msg']);
        }

        $server = new \app\adminapiv3\service\InstallService();
        $server->online($authRes);

        return $this->jsonOutPut();
    }

    /**
     * @name 离线授权
     * @author wx
     * @date 2019/11/28 10:55
     */
    public function offline()
    {
        $this->isInstall();

        $file = request()->file('file');

        if (!$file) {
            returnErrJson(122,'请上传授权文件');
        }

        $server = new InstallService();
        $server->offline($file);

        return $this->jsonOutPut();
    }

    /**
     * @name 下载主机码文件
     * @author wx
     * @date 2019/11/28 14:47
     */
    public function downloadHostFile()
    {
        $data['ip'] = $_SERVER['SERVER_ADDR'];
        $data['port'] = $_SERVER['SERVER_PORT'];
        $data['path'] = 'static/host/hostkey.key';

        $server = new ServerAuthService();
        $server->createHostFile();

        return $this->jsonOutPut($data);
    }


    /**
     * @name 获取模块
     * @author wx
     * @date 2020/1/8 20:37
     */
    public function getModule()
    {
        $this->isInstall();

        $content = file_get_contents('./Install/auth.json');
        $arr = json_decode($content, true);


        $list = array();
        $oldArr = array(
            array('name' => '代理(中间件)','type' => 'proxy'),
        );

        foreach ($arr as $k => $v) {
            if ($v['product_key'] == 'netfilter') {
                $tmp['name'] = $v['module_name'].'(中间件)';
                $tmp['type'] = $v['product_key'];
                $list[] = $tmp;
            }

            $mode = $v['mode'];//1标准版,2分布式版
        }


        $allArr = array_merge($list, $oldArr);

        $data['code'] = 200;
        $data['msg'] = 'success';
        $data['data'] = $allArr;
        $data['mode'] = $mode;
        return json($data);
    }


    /**
     * @name 设置代理服务器地址
     * @author wx
     * @date 2019/12/10 10:16
     */
    public function addProxyIp(Request $request)
    {
        $this->isInstall();

        $params = $request->only(['ip', 'port', 'mysql'],'post');

        $this->validate($params, 'Install.addProxyIp');
        $ip = $params['ip'];
        $module = $params['port'];
        $mysqlIp = $params['mysql'];


        $server = new InstallService();
        $server->addProxy($ip, $module, $mysqlIp);

        return $this->jsonOutPut();
    }


    /**
     * @name 用户名配置
     * @author wx
     * @date time
     */
    public function userConfig(Request $request)
    {
        $this->isInstall();
        $data = $request->only(['real_name', 'show_name', 'password'],'post');

        $this->validate($data, 'Install.userConfig');

        $server = new InstallService();
        $server->adduser($data);

        //完成安装的事情
        $this->install();
        return $this->jsonOutPut();
    }

    /**
     * @name 安装完成的事情
     * @author wx
     * @date 2019/12/2 13:49
     */
    public function install()
    {
        $authPath = './Install/auth.json';
        if (!file_exists($authPath)) {
            returnErrJson(123, '您未授权,请先授权');
        }
        $content = file_get_contents($authPath);
        $authArr = json_decode($content, true);

        //1. 授权相关数据入库
        $authServer = new ServerAuthService();
        $authServer->handleData($authArr);

        //2. IP白名单入库
        $ip = $_SERVER['REMOTE_ADDR'];
        $allowIpInfo = Db::name('server_allow_ip')->where('ip', $ip)->find();

        if(empty($allowIpInfo)){
            $addAllowIp['ip'] = $ip;
            $addAllowIp['ctime'] = time();
            $addAllowIp['login_time'] = 0;

            Db::name('server_allow_ip')->insert($addAllowIp);
        }

        //3. ./Install/install.lock创建安装文件
        file_put_contents('./Install/install.lock','install finish time:'.date('Y-m-d H:i:s',time()));
    }
}